/*
 * @Author: 邱狮杰
 * @Date: 2021-09-05 12:02:56
 * @LastEditTime: 2021-09-05 15:36:19
 * @FilePath: /new-hope/src/utils/bus.ts
 * @Description: 描述
 */
export default class Bus {
  eventList: Map<string, Function[]>;
  constructor() {
    this.eventList = new Map();
  }
  // 发布
  emit<T extends unknown>(key: string, val: T) {
    // 如果事件中心不存在该事件回调直接抛错
    if (!this.eventList.has(key)) return;
    const eventCb: Function[] = this.eventList.get(key) || [];
    eventCb.forEach((fn) => fn(val));
  }
  // 订阅
  on<T>(key: string, cb: (res: T) => void) {
    if (!this.eventList.get(key)) {
      this.eventList.set(key, []);
    }
    const token = this.eventList.get(key);
    token && token.push(cb);
  }
  // 销毁
  off(key: string) {
    if (!this.eventList.has(key)) return;
    this.eventList.delete(key);
  }
}
